/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 *
 * @version 1.0
 */
package shop.controller.front.order;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.services.front.order.OrderService;
import shop.services.front.order.bean.Order;
import shop.services.front.orderdetail.OrderdetailService;
import shop.services.front.orderdetail.bean.Orderdetail;
import shop.services.front.product.ProductService;
import shop.services.front.product.bean.Product;
import shop.services.front.record.RecordService;
import shop.services.front.record.bean.Record;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @类名称：OrderController
 * @创建人：Ltz
 * @创建时间：2017-09-20 下午15:48:44
 * @版本号：1.0
 * @描述：
 */
@Controller
@RequestMapping("/front/order/")
public class OrderController extends FrontBaseController<Order> {
    private final  static  String PRODUCT_CHECK_STATUS_END="5";
    @Resource
    private OrderService orderService;
    @Resource
    private OrderdetailService orderdetailService;
    @Resource
    private UserService userService;
    @Resource
    private ProductService productService;
    @Resource
    private RecordService recordService;

    @Override
    public Services<Order> getService() {
        return orderService;
    }


    /**
     * 跳转到订单列表页面
     *
     * @return
     */
    @RequestMapping("toOrderList")
    public String toOrderList() {
        return "/front/order/allOrder";
    }

    /**
     * 跳转到订单详情页面（个人中心入口）
     *
     * @return
     */
    @RequestMapping("toOrderDetail")
    public String toOrderDetail() {
        return "/front/order/finishOrder";
    }

    /**
     * 跳转到订单详情页面（购物车入口）
     *
     * @return
     */
    @RequestMapping("toCartOrderDetail")
    public String toCartOrderDetail() {
        return "/front/order/cartOrderDetail";
    }

    /**
     * 跳转到订单详情页面（商品详情入口）
     *
     * @return
     */
    @RequestMapping("toProductOrderDetail")
    public String toProductOrderDetail() {
        return "/front/order/orderDetail";
    }

    /**
     * 跳转到发货页面
     *
     * @return
     */
    @RequestMapping("toSendGoods")
    public String toSendGoods() {
        return "/front/group/sendGoods";
    }


    /**
     * 查询订单列表
     * @param order
     * @return orderList
     */
    @RequestMapping(value = "selectOrderList", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderList(HttpServletRequest request, Order order) {
        JSONResult jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute("userInfo");
        order.setUserID(user.getId());
        List<Order> orderList = orderService.selectList(order);//查询用户订单列表
        for (int i = 0; i < orderList.size(); i++) {//遍历订单列表
            Order orderInfo = orderList.get(i);
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOrderID(orderInfo.getId());//赋值
            orderList.get(i).setOrderdetails(orderdetailService.selectOrderDetailList(orderdetail));//查询订单详情列表
            //添加商品审核状态
            Product product = new Product();
            product.setId(orderList.get(i).getOrderdetails().get(0).getProductID());
            product = productService.selectOne(product);
            orderList.get(i).setProductCheckStatus(product.getCheckStatus());
        }
        jsonResult.setData(orderList);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 查询分享订单列表
     *
     * @param order
     * @return orderList
     */
    @RequestMapping(value = "selectShareOrder", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectShareOrder(HttpServletRequest request, Order order) {
        JSONResult jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute("userInfo");
        order.setUserID(user.getId());
        List<Order> orderList = orderService.selectList(order);//查询用户订单列表
        for (int i = 0; i < orderList.size(); i++) {//遍历订单列表
            Order orderInfo = orderList.get(i);
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOrderID(orderInfo.getId());//赋值
            orderList.get(i).setOrderdetails(orderdetailService.selectOrderDetailList(orderdetail));//查询订单详情列表
            //剔除开团结束的订单
            Product product = new Product();
            product.setId(orderList.get(i).getOrderdetails().get(0).getProductID());
            product = productService.selectOne(product);
            if (PRODUCT_CHECK_STATUS_END.equals(product.getCheckStatus()))
                orderList.remove(i);
        }
        jsonResult.setData(orderList);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 查询订单详情（个人中心入口）
     *
     * @return
     */
    @RequestMapping(value = "selectOrderDetail", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderDetail(Orderdetail orderdetail) {
        Orderdetail rs = new Orderdetail();
        rs.setOrderID(orderdetail.getOrderID());
        List<Orderdetail> rsList = orderdetailService.selectOrderDetailList(rs);
        return new JSONResult(rsList, true);
    }

    /**
     * 查询用户订单地址
     *
     * @param order
     * @return
     */
    @RequestMapping(value = "selectOrderAddress", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderAddress(HttpServletRequest request, Order order) {
        order = orderService.selectOne(order);
        jsonResult = new JSONResult();
        jsonResult.setData(order);
        return jsonResult;
    }

    /**
     * 批量发货（一键发货）
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "updateOrders", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateOrders(Order order, @RequestParam(value = "ids[]") String[] ids) throws Exception {
        jsonResult = new JSONResult();
        for (int i = 0; i < ids.length; i++) {
            order.setId(ids[i]);
            order.setStatus("send");
            orderService.update(order);
        }
        return jsonResult;
    }

    /**
     * 查询团购订单
     *
     * @param product
     * @return orderList
     */
    @RequestMapping(value = "selectGroupOrder", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectGroupOrder(Product product) {
        JSONResult jsonResult = new JSONResult();
        //查询团购订单列表
        Orderdetail orderdetail = new Orderdetail();
        orderdetail.setProductID(product.getId());
        List<Orderdetail> orderdetailList = orderdetailService.selectHistoryOrderdetail(orderdetail);
        List<Order> orderList = new ArrayList<>();
        for (Orderdetail orderdetailInfo : orderdetailList) {
            Order order = new Order();
            order.setId(orderdetailInfo.getOrderID());
            order = orderService.selectOne(order);
            if ("y".equals(order.getIsGroup()) && order.getGroupNumber() != 0 && "pass".equals(order.getStatus())) {
                orderList.add(order);
            }
        }
        //添加订单详情
        for (Order orderInfo : orderList) {
            Orderdetail orderdetailInfo = new Orderdetail();
            orderdetailInfo.setOrderID(orderInfo.getId());
            orderInfo.setOrderdetails(orderdetailService.selectOrderDetailList(orderdetailInfo));
            //添加用户信息
            User user = new User();
            user.setId(orderInfo.getUserID());
            user = userService.selectOne(user);
            orderInfo.setUserName(user.getNickname());
            orderInfo.setUserIcon(user.getIcon());
        }
        jsonResult.setData(orderList);
        return jsonResult;
    }

    /**
     * 查询预定团购订单
     *
     * @param product
     * @return orderList
     */
    @RequestMapping(value = "selectReserveGroupOrder", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectReserveGroupOrder(Product product) {
        JSONResult jsonResult = new JSONResult();
        //查询团购订单列表
        Orderdetail orderdetail = new Orderdetail();
        orderdetail.setProductID(product.getId());
        List<Orderdetail> orderdetailList = orderdetailService.selectHistoryOrderdetail(orderdetail);
        List<Order> orderList = new ArrayList<>();
        for (Orderdetail orderdetailInfo : orderdetailList) {
            Order order = new Order();
            order.setId(orderdetailInfo.getOrderID());
            order = orderService.selectOne(order);
            if ("y".equals(order.getIsGroup()) && order.getGroupNumber() != 0
                    && "pass".equals(order.getStatus()) && "y".equals(order.getIsReserve())) {
                orderList.add(order);
            }
        }
        //添加订单详情
        for (Order orderInfo : orderList) {
            Orderdetail orderdetailInfo = new Orderdetail();
            orderdetailInfo.setOrderID(orderInfo.getId());
            orderInfo.setOrderdetails(orderdetailService.selectOrderDetailList(orderdetailInfo));
            //添加用户信息
            User user = new User();
            user.setId(orderInfo.getUserID());
            user = userService.selectOne(user);
            orderInfo.setUserName(user.getNickname());
            orderInfo.setUserIcon(user.getIcon());
        }
        jsonResult.setData(orderList);
        return jsonResult;
    }

    /**
     * 查询待发货订单(日期分组)
     *
     * @param order
     * @return orderList
     */
    @RequestMapping(value = "selectSendOrderByDay", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectSendOrderByDay(HttpSession session, Order order) {
        JSONResult jsonResult = new JSONResult();
        //查询团购订单列表
        User seller = (User) session.getAttribute("userInfo");
        order.setMerchantID(seller.getId());
        List<Order> orderList = orderService.selectSendOrderByDay(order);
        //添加订单详情
        for (Order orderInfo : orderList) {
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOrderID(orderInfo.getId());
            orderInfo.setOrderdetails(orderdetailService.selectOrderDetailList(orderdetail));
            //添加买家信息
            User buyer = new User();
            buyer.setId(orderInfo.getUserID());
            buyer = userService.selectOne(buyer);
            orderInfo.setUserName(buyer.getNickname());
            orderInfo.setUserIcon(buyer.getIcon());
        }
        jsonResult.setData(orderList);
        return jsonResult;
    }

    /**
     * 余额抵扣
     *
     * @param order
     * @return
     */
    @RequestMapping(value = "deductionOrder", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deductionOrder(HttpSession session, Order order) {
        User user = (User) session.getAttribute("userInfo");
        order.setUserID(user.getId());
        order.setStatus("pass");
        order.setGroupNumber(1);
        int orderID = orderService.insert(order);
        user.setWalletMoney(user.getWalletMoney().subtract(order.getDeduction()));
        userService.update(user);
        Record record =new Record();
        record.setUserID(user.getId());
        record.setTransType("3");
        record.setMoney(order.getDeduction());
        recordService.insert(record);//生成钱包明细
        return new JSONResult<>(orderID, true);
    }

}
